# _*_ coding utf-8 _*_
# FILENAME：.py
# DESCRIPTION: 
# AUTH: 
# DATE: 2022/6/83:49 下午
from PyQt5.QtCore import Qt, QRect, QMetaObject, QCoreApplication
from PyQt5.QtGui import QStandardItem
from PyQt5.QtWidgets import *
from sqlalchemy import desc

from components.DataGridComponent import DataGridComponent
from models.baseModel import get_session
from models.factoryModel import FactoryModel
from models.produceQueueModel import ProduceQueueModel


class SelectProduceQueue(QMainWindow):
    def __init__(self, parentWidget):
        super().__init__()
        self.parentWidget = parentWidget
        self.setupUi(self)

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.setWindowModality(Qt.ApplicationModal)
        MainWindow.resize(600, 400)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        grid = QGridLayout()  # 网格布局
        # tableview
        self.dataGrid = ProduceQueueDataGrid(self, self.parentWidget)
        '''加入布局'''
        grid.addWidget(self.dataGrid, 0, 0, 1, 10)

        self.centralwidget.setLayout(grid)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QRect(0, 0, 550, 26))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "选择生产队列"))

# DataGrid组件
class ProduceQueueDataGrid(DataGridComponent):
    def __init__(self, parentWidget, form):
        super(ProduceQueueDataGrid, self).__init__()
        self.parentWidget = parentWidget
        self.form = form
        self.setDataModelHeaders()
        self.query_click()

    def setDataModelHeaders(self):
        self.dataModel.setHeaderData(0, Qt.Horizontal, '编号')
        self.dataModel.setHeaderData(1, Qt.Horizontal, '版本名称')
        self.dataModel.setHeaderData(2, Qt.Horizontal, '更新时间')
        self.dataModel.setHeaderData(3, Qt.Horizontal, '操作')
        # 设置列宽
        self.tableView.setColumnWidth(0, 50)
        self.tableView.setColumnWidth(1, 300)
        self.tableView.setColumnWidth(2, 150)
        self.tableView.setColumnWidth(3, 100)

    # 得到记录数，重写
    def getTotalRecordCount(self):
        rowCount = self.query_total()
        print('rowCount=' + str(rowCount))
        return rowCount

    # 记录查询，重写
    def recordQuery(self, limitIndex):
        data = self.page(limitIndex, self.PageRecordCount, self.edit_no.text(), self.edit_vension.text())
        if len(data) != 0:
            self.tableView.setItemDelegateForColumn(3, MyButtonDelegate(self))
            self.dataModel.clear()
            for i in range(len(data)):
                # 添加
                newItem = QStandardItem(str(data[i].id))
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                self.dataModel.setItem(i, 0, newItem)

                newItem = QStandardItem(str(data[i].version_name))
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                self.dataModel.setItem(i, 1, newItem)

                newItem = QStandardItem(str(data[i].create_date))
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                self.dataModel.setItem(i, 2, newItem)

                newItem = QStandardItem("")
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                self.dataModel.setItem(i, 3, newItem)
        else:
            newItem = QStandardItem('')
            newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
            self.dataModel.setItem(0, 0, newItem)

            newItem = QStandardItem('')
            newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
            self.dataModel.setItem(0, 1, newItem)

            newItem = QStandardItem('')
            newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
            self.dataModel.setItem(0, 2, newItem)

            newItem = QStandardItem("")
            newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
            self.dataModel.setItem(0, 3, newItem)
        self.setDataModelHeaders()

    # 重写查询方法
    def query_click(self):
        self.refresh()

    # 分页查询列表
    def page(self, limitIndex=0, pageRecordCount=0, no=0, version=None):
        # 获取dbsession
        session = get_session()
        # 拼接查询
        my_query = session.query(ProduceQueueModel)
        my_query = my_query.filter(ProduceQueueModel.is_del == 0)
        # 拼接查询条件
        if version != "":
            my_query = my_query.filter(ProduceQueueModel.version_name.like("%"+version+"%"))
        if no != "":
            my_query = my_query.filter(ProduceQueueModel.id == no)
        # 拼接排序条件
        my_query = my_query.order_by(desc(ProduceQueueModel.id))
        # 分页
        my_query = my_query.offset(limitIndex).limit(pageRecordCount)
        # 执行查询
        model = my_query.all()
        session.close()
        return model

    # 查询数据总量
    def query_total(self, version=None, factory=None):
        # 获取dbsession
        session = get_session()
        # 拼接查询
        my_query = session.query(ProduceQueueModel)
        my_query = my_query.filter(ProduceQueueModel.is_del == 0)
        # 拼接查询条件
        if version:
            my_query = my_query.filter(ProduceQueueModel.version_name == version)
        if factory:
            my_query = my_query.filter(ProduceQueueModel.factory_id == factory)
        # 执行查询
        count = my_query.count()
        session.close()
        return count

    # 编辑
    def select_click(self):
        button = self.sender()
        if button:
            cell = button.index
            row = cell[0]
            id = self.dataModel.item(row, 0).text()
            name = self.dataModel.item(row, 1).text()
            self.form.production_queue_edit.setText(name)
            self.form.setProduceQueueId(id)
        self.parentWidget.close()

class MyButtonDelegate(QItemDelegate):
    def __init__(self, parent=None):
        super(MyButtonDelegate, self).__init__(parent)

    def paint(self, painter, option, index):
        if not self.parent().tableView.indexWidget(index):
            btn_select = QPushButton(
                self.tr('选择'),
                self.parent(),
                clicked=self.parent().select_click
            )
            # btn_select.setStyleSheet('''
            #                         color: #fff;
            #                                   background-color : #6c757d;
            #                                   ''')
            btn_select.index = [index.row(), index.column()]

            # 布局
            h_box_layout = QHBoxLayout()
            h_box_layout.addWidget(btn_select)
            h_box_layout.setContentsMargins(0, 0, 0, 0)
            h_box_layout.setAlignment(Qt.AlignCenter)
            widget = QWidget()
            widget.setLayout(h_box_layout)
            self.parent().tableView.setIndexWidget(
                index,
                widget
            )